﻿using CCSSolderUI.Common.Event;
using CCSSolderUI.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class MSensorDialogViewModel : BindableBase, IDialogAware
    {
        #region 变量
        bool StopFlag = false;
        Param param;
        string partNumber;
        IEventAggregator _eventAggregator;
        #endregion
        #region 属性
        private double hDistance;
        public double HDistance
        {
            get { return hDistance; }
            set { SetProperty(ref hDistance, value); }
        }
        private double hDist1;
        public double HDist1
        {
            get { return hDist1; }
            set { SetProperty(ref hDist1, value); }
        }
        private double hDist2;
        public double HDist2
        {
            get { return hDist2; }
            set { SetProperty(ref hDist2, value); }
        }
        #endregion
        #region 导航
        public string Title => "传感器";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            StopFlag = true;
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            partNumber = parameters.GetValue<string>("PartNumber");
            LoadParam();
            StopFlag = false;
            Run();
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> getHDistCommand;
        public DelegateCommand<object> GetHDistCommand =>
            getHDistCommand ?? (getHDistCommand = new DelegateCommand<object>(ExecuteGetHDistCommand));
        private DelegateCommand saveButtonCommand;
        public DelegateCommand SaveButtonCommand =>
            saveButtonCommand ?? (saveButtonCommand = new DelegateCommand(ExecuteSaveButtonCommand));

        private void ExecuteSaveButtonCommand()
        {
            param.HDist1 = HDist1;
            param.HDist2 = HDist2;
            try
            {
                string jsonString = JsonConvert.SerializeObject(param, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partNumber, "Param.json"), jsonString);
                MessageBox.Show("保存完成", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MSensorDialog", Type = "Update", Content = null });
            }
            catch (Exception ex)
            {
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MSensorDialog", Type = "Print", Content = ex.Message });
            }
        }

        private void ExecuteGetHDistCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "1":
                    if (MessageBox.Show($"确认重新设置板①探高吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        HDist1 = HDistance;
                    }
                    break;
                case "2":
                    if (MessageBox.Show($"确认重新设置板②探高吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        HDist2 = HDistance;
                    }
                    break;
                default:
                    break;
            }
        }
        #endregion
        #region 构造函数
        public MSensorDialogViewModel(IEventAggregator ea)
        {
            _eventAggregator = ea;
            _eventAggregator.GetEvent<MessagePrintEvent>().Subscribe(MessageReceived);
        }
        #endregion
        #region 功能函数
        private void MessageReceived(Common.Event.Message obj)
        {
            switch (obj.Type)
            {
                case "Select":
                    partNumber = obj.Content;
                    LoadParam();
                    break;
                case "Update":
                    if (obj.Sender != "MSensorDialog")
                    {
                        LoadParam();
                    }
                    break;
                default:
                    break;
            }
        }
        async void Run()
        {
            while (!StopFlag)
            {
                try
                {
                    if (PLCModbus.Instance.Connected)
                    {
                        var aa = PLCModbus.Instance.ReadDRegisters(100, 1);
                        if (aa != null)
                        {
                            var bb = Convert.ToInt16(aa[0].ToString("X4"), 16);
                            HDistance = Math.Round(bb / 20000.0 * 280 - 140 + 300, 1);
                        }
                    }
                }
                catch { }
                await Task.Delay(200);
            }
        }
        private void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partNumber, "Param.json"));
                param = JsonConvert.DeserializeObject<Param>(jsonString);
                HDist1 = param.HDist1;
                HDist2 = param.HDist2;
            }
            catch (Exception ex)
            {
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "MSensorDialog", Type = "Print", Content = ex.Message });
            }
        }
        #endregion
    }
}
